<script setup>
import {
  BMap,
  BLocation,
  BZoom,
  BControl,
  BNavigation3d,
  BMarker,
  BInfoWindow,
  BPolygon, BCityList, useBrowserLocation
} from 'vue3-baidu-map-gl'
import {onBeforeMount,ref} from "vue";
import moment from "moment/moment";
import {nanoid} from "nanoid";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
//----------------------------------------------------------------------------工具函数
//获取当前日期的字符串
function getDateString(){
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  return year + '-' + month + '-' + day;

}
//----------------------------------------------------------------------------地图相关
//地图示例
const map = ref()
const { get, location, isError } = useBrowserLocation(null, () => {
  mapData.value.center = location._value.point
  let province = location._value.address.province
  let formData=  new FormData()
/*  formData.append("province", province)
  request.post("http://localhost:8090/user/map/updateUserProvince",formData)
      .then(res=>{

      })
      .catch(err=>{
        console.log(err)
      })*/
})
//地图的各种数据
let mapData = ref({
  center:{lng: 116.41821325751386, lat: 39.88712161341779},
  zoom:14
})
//当前绘制的类型
let drawType = ref("多边形")
//地图鼠标左键单击事件，记录点击坐标
function MapClick(obj){
}
//地图鼠标右键单击事件，添加标记点
function MapRightClick(obj){
  if(drawType.value === "标记点"){
    let point = {}
    point.pid = nanoid(6)
    point.position = obj.latlng
    point.title = "标记点信息"
    point.info = ""
    point.addDate = moment().format('YYYY-MM-DD')
    point.showDetail = false
    point.icon = "simple_red"
    pointData.value.push(point)
    AddPoint(point)
  }

}
//地图初始化
function MapInit(map){
  get()
}

//----------------------------------------------------------------------------标记点绘制相关
//标记点数据,simple_red为正常图标，loc_red为定位选中图标
let pointData = ref([
  {
    pid:"123456",
    position:{lng:121.44627103426541,lat:31.23934912313566},
    title:"标记点信息",
    info:"纳米号等四艘发动发动机送哦富士康范德萨",
    addDate:"2024-12-04",
    showDetail:false,
    icon:"simple_red"
  }
])
//修改框是否显示
let dialogFormVisible = ref(false)
let pointWindowEditTxt = ref("")
let currentPid = ref("123")//选中编辑的标记点的pid
//点击标记点显示详细坐标
function PointClick(item){
  item.showDetail = true
}
//点击标记点定位按钮，地图跳转到该点位置
function PointLocationBtnClick(row){
  mapData.value.center.lat = row.position.lat
  mapData.value.center.lng = row.position.lng
  pointData.value.forEach(point=>{
    if(row.pid !== point.pid)point.icon = "simple_red"
    else point.icon = "loc_red"
  })
}
//点击标记修改按钮，可以修改标记点窗口的备注信息
function PointEditInfo(row){
  currentPid.value = row.pid
  dialogFormVisible.value = true
  request.get("http://localhost:8090/user/map/getUserPointWindowInfoByPid",{
    params:{pid:row.pid}
  })
      .then(res=>{
        if(res.data.code === 200){
          pointWindowEditTxt.value = res.data.data
        }
      })
      .catch(err=>{
        console.log(err)
      })
}
//取消编辑
function cancelUpdatePointWindowTxt(){
  dialogFormVisible.value = false
  ElMessage({
    type:"info",
    message:"取消修改"
  })
}
//更新数据库中的信息
function updatePointWindowTxt(){
  let formData = new FormData()
  formData.append("pid",currentPid.value)
  formData.append("info",pointWindowEditTxt.value)
  request.post("http://localhost:8090/user/map/updateUserPointWindowInfoByPid",formData)
      .then(res=>{
        if(res.data.code === 200){
          ElMessage({
            type:"success",
            message:"修改成功"
          })
          dialogFormVisible.value = false
          pointData.value = res.data.data
        }
        else{
          ElMessage({
            type:"error",
            message:"修改失败"
          })
        }
      })
      .catch(err=>{
        console.log(err)
      })
}
//点击标记点删除按钮，删除该标记点
function PointDeleteBtnClick(row){
  ElMessageBox.confirm(
      '您确定要删除该标记点吗？',
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(()=>{
        let pid = row.pid
        DeletePoint(pid)
        pointData.value = pointData.value.filter((item)=>{
          return item.pid !== pid
        })
      })
      .catch(()=>{
        ElMessage({
          type: 'success',
          message: '取消删除',
        })
      })


}
//新增点坐标到数据库
function AddPoint(point){
  request.post("http://localhost:8090/user/map/addMarkerPoint",point)
      .then(res=>{
        if(res.data.code === 200){
          ElMessage({
            type: 'success',
            message: '添加成功',
          })
        }
        else{
          ElMessage({
            type: 'error',
            message: res.data.msg,
          })
        }
      })
      .catch(err=>{
        console.log(err)
      })
}
//删除数据库中点坐标
function DeletePoint(pid){
  let formData = new FormData()
  formData.append("pid",pid)
  request.post("http://localhost:8090/user/map/deleteMarkerPointByPid",formData)
      .then(res=>{
        if(res.data.code === 200){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
        else{
          ElMessage({
            type: 'error',
            message: res.data.msg,
          })
        }
      })
      .catch(err=>{
        console.log(err)
      })
}
//----------------------------------------------------------------------------多边形绘制相关
/*const { result, convert, status,isLoading} = usePointConvertor()
//和Polygon组件绑定的数据
let polygon = ref({
  points:[],
  isDelete:true,
  editable:true,
  fillColor:"#bbc4b3"
})
//记录地图中实时变化的多边形点(组件关闭时传送给后端保存到数据库)
let tempPolygonPointData = ref([])
function PolygonLineUpdate(obj){
  if(polygon.value.isDelete)return
  let points = []
  for (let i = 0; i < obj.currentTarget.points.length; i++) {
    let latLng = {lng:obj.currentTarget.points[i].lng, lat:obj.currentTarget.points[i].lat}
    points.push(latLng)
  }
  convert(points, CoordinatesFromType['COORDINATES_BD09_MC'], CoordinatesToType['COORDINATES_BD09'])
  setTimeout(()=>{
    if(result._rawValue)tempPolygonPointData.value = result._rawValue;
  },600)



}
//定位到多边形中点位置
function LocationPolygon(){
  let latSum = 0,lngSum = 0
  for (let i=0;i<tempPolygonPointData.value.length;i++) {
    latSum += tempPolygonPointData.value[i].lat
    lngSum += tempPolygonPointData.value[i].lng
  }
  mapData.value.center.lat = latSum/tempPolygonPointData.value.length
  mapData.value.center.lng = lngSum/tempPolygonPointData.value.length
  console.log(mapData.value.center)
}
//删除多边形
function DeletePolygon(){
  ElMessageBox.confirm(
      '您确定要删除该标记点吗？',
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(()=>{
        request.post("http://localhost:8090/user/map/deletePolygonArea")
            .then(res=>{
              if(res.data.code === 200){
                polygon.value.isDelete = true
                tempPolygonPointData.value = []
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
              }
              else{
                ElMessage({
                  type: 'error',
                  message: '删除失败',
                })
              }
            })
            .catch(err=>{
              ElMessage({
                type: 'error',
                message: '网络错误',
              })
            })
      })
      .catch(()=>{
        ElMessage({
          type: 'success',
          message: '取消删除',
        })
      })


}
//保存多边形区域数据
function SavePolygonData(){
  let param = {
    points:tempPolygonPointData.value,
    editable:polygon.value.editable ? 1 : 0,
    fillColor:polygon.value.fillColor,
    addDate:getDateString()
  }
  request.post("http://localhost:8090/user/map/addPolygonArea",param)
      .then(res=>{
        console.log("SavePolygonData",res)
      })
      .catch(err=>{
        console.log(err)
      })
}
//创建多边形
function DrawPolygon(){
  if(tempPolygonPointData.value.length < 3)return
  polygon.value.isDelete = false
  tempPolygonPointData.value.push(tempPolygonPointData.value[0])
  polygon.value.points = tempPolygonPointData.value
  SavePolygonData()
}
let polygonPos = ref({
  lat: 39.903573469941804,
  lng: 116.397947485208
})
let polygonWindowShow = ref(false)*/
//----------------------------------------------------------------------------新多边形绘制相关
//接收后端传来的参数
let polygonData = ref({
  points:[]
})
//信息窗口位置
let polygonWindowPos = ref({
  lat: 27.604453580185787,
  lng: 102.5400076306469
})
//信息窗口是否显示
let polygonWindowShow = ref(false)
//用户名
let username = ref("张三")
//定位到多边形区域重点
function LocationPolygon(){
  let points = polygonData.value.points
  let latSum = 0,lngSum = 0
  for (let i=0;i<points.length;i++) {
    latSum += points[i].lat
    lngSum += points[i].lng
  }
  mapData.value.center.lat = latSum/points.length + Math.random() * 0.00000000001
  mapData.value.center.lng = lngSum/points.length + Math.random() * 0.00000000001
  mapData.value.zoom = 20;
}
//鼠标点击多边形区域
function OnPolygonMouseOver(e){
  polygonWindowShow.value = true
}
function OnPolygonMouseOut(e){
  polygonWindowShow.value = false
}
//----------------------------------------------------------------------------生命周期函数
//组件挂载前拿到地图坐标数据
onBeforeMount(()=>{
  //获取用户的标记点数据
  request.get("http://localhost:8090/user/map/getAllMarkerPointByUid")
      .then(res=>{
        if(res.data.data !== null)pointData.value = res.data.data
      })
      .catch(err=>{
        console.log(err)
      })

  //获取生成的矩形区域
  request.get("http://localhost:8090/user/map/getRiceReactArea")
      .then(res=>{
        if(res.data.code === 200){
          polygonData.value = res.data.data
          let leftBottomPoint = res.data.data.leftBottom
          let rightTopPoint = {lng:leftBottomPoint.lng + 0.0005, lat:leftBottomPoint.lat + 0.0005}
          let leftTopPoint = {lng:leftBottomPoint.lng, lat:rightTopPoint.lat}
          let rightBottomPoint = {lng:rightTopPoint.lng, lat:leftBottomPoint.lat}
          let points = []
          points.push(leftBottomPoint)
          points.push(leftTopPoint)
          points.push(rightTopPoint)
          points.push(rightBottomPoint)
          let latSum = 0,lngSum = 0
          for (let i=0;i<points.length;i++) {
            latSum += points[i].lat
            lngSum += points[i].lng
          }
          polygonWindowPos.value.lng = lngSum / points.length
          polygonWindowPos.value.lat = latSum / points.length
          points.push(leftBottomPoint)
          polygonData.value.points = points
        }
      })
      .catch(err=>{
        console.log(err)
      })
  //获取当前用户的用户名
  request.get("http://localhost:8090/user/getUserNameByUid")
      .then(res=>{
        if(res.data.code === 200)username.value = res.data.data
      })
      .catch(err=>{
        console.log(err)
      })
})

</script>

<template>
  <div class="container">
    <el-dialog v-model="dialogFormVisible" title="标记点信息修改" width="500" >
      <el-form-item label="备注信息">
        <el-input v-model="pointWindowEditTxt"></el-input>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpdatePointWindowTxt">取消</el-button>
          <el-button type="primary" @click="updatePointWindowTxt">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <BMap
          :enableScrollWheelZoom="true" :center="mapData.center" :zoom="mapData.zoom"
          @click="MapClick" @rightclick="MapRightClick"
          @initd="MapInit"
          :plugins="['TrackAnimation']"
          ref="map"
          height="100%"
    >
      <BControl anchor="BMAP_ANCHOR_TOP_RIGHT"
                style="width: 300px;height:300px;background-color:rgba(0.5,0.5,0.5,.1);padding-left: 10px;padding-right: 10px; border-radius: 15px; margin-right: -80px"
      >
        <el-radio-group v-model="drawType">
          <el-radio value="标记点" label="我的标记点"></el-radio>
          <el-radio value="多边形" label="种植区域"></el-radio>
        </el-radio-group>
        <el-container v-if="drawType === '标记点'">
          <el-table :data="pointData" stripe style="width: 100%; height: 205px;">
            <el-table-column prop="pid" label="id值" width="80px"/>
            <el-table-column prop="addDate" label="添加日期" width="96px"/>
            <el-table-column label="操作" width="200px">
              <template #default="scope">
                <el-button size="small" type="primary" @click="PointLocationBtnClick(scope.row)">
                  定位
                </el-button>
                <el-button size="small" type="primary" @click="PointEditInfo(scope.row)">
                  备注
                </el-button>
                <el-button size="small" type="danger" @click="PointDeleteBtnClick(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-container>
        <el-container v-if="drawType === '多边形'" class="polygon-container">
          <el-table :data="polygonData.points" stripe style="width: 100%; height: 50%; background-color:pink;">
            <el-table-column type="index" width="30" />
            <el-table-column prop="lng" label="经度" width="140px"/>
            <el-table-column prop="lat" label="纬度" width="140px"/>
          </el-table>
          <el-container style="height: 50%;display: flex;flex-direction: column;justify-content: flex-start">
            <el-container>
              <el-button type="primary"
                         @click="LocationPolygon"
                         :disabled="polygonData.points.length === 0"
                         style="width: 30%; margin: 10px auto; border-radius: 10px">定位</el-button>

            </el-container>
          </el-container>
        </el-container>
      </BControl>
      <BCityList />
      <BZoom />
      <BLocation />
      <BNavigation3d anchor="BMAP_ANCHOR_BOTTOM_LEFT"/>
      <BMarker v-for="item in pointData" :key="item.pid" :position="item.position" :icon=item.icon @click="PointClick(item)"/>
      <BInfoWindow v-for="item in pointData"
                   :key="item.pid"
                   v-model:show="item.showDetail"
                   :position="item.position"
                   :title="item.title"
                   enableCloseOnClick
                   :offset="{x: 0,y: -10}"
      >
        <div class="infoWindow-content">
          <p>经度：{{item.position.lng}}</p>
          <p>纬度：{{item.position.lat}}</p>
          <hr>
          <p>{{item.info}}</p>
        </div>

      </BInfoWindow>
      <BPolygon
          :enableEditing="false"
          :path="polygonData.points"
          fill-color="#409eff"
          v-if="polygonData.points.length > 0"
          stroke-color="#000"
          :stroke-opacity="0.4"
          :stroke-weight="1"
          @mouseover="OnPolygonMouseOver"
          @mouseout="OnPolygonMouseOut"
      />
      <BInfoWindow
          v-model:show="polygonWindowShow"
          :position="polygonWindowPos"
          title="种植区域概况"
          enableCloseOnClick
          :offset="{x: 0,y: 0}"
      >
        <div class="infoWindow-content">
          <p>稻田主人：{{username}}</p>
          <p>数据更新日期：{{polygonData.uploadDate}}</p>
          <p>水稻患病率：{{((polygonData.totalRiceCount - polygonData.status1Num)*100/polygonData.totalRiceCount).toFixed(2)}}%</p>
        </div>
      </BInfoWindow>
    </BMap>

  </div>

</template>

<style scoped>
.container {
  margin: 5px 5px;
  border-radius: 20px;
}
.polygon-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.el-container {
  width: 100%;
}
.el-radio-group {
  margin-bottom: 10px;
}
p {
  height: 10px;
}
.el-text {
  width: 300px;
}
</style>